//go:build ignore
// +build ignore

package main

import (
	"fmt"
	"net"
	"strings"
)

func main() {
	// 服务端监听结构体
	listener, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("err =", err)
		return
	}
	for {
		// 取得链接
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("err =", err)
			continue
		}
		// 对每个链接开启一个协程
		go func(conn net.Conn) {
			defer conn.Close()

			// 打印是哪个ip:port链接过来的
			addr := conn.RemoteAddr().String()
			fmt.Println("connect from", addr)

			// 给链接发送链接成功信息
			sss_info := []byte(fmt.Sprintf("Hello %s ! Please give me some words.\n", addr))
			conn.Write(sss_info)

			// 持续对话
			for {
				// 获取内容
				content := make([]byte, 1024)
				n, err := conn.Read(content)
				if err != nil {
					fmt.Println("err =", err)
					return
				}
				fmt.Printf("[%s] give msg: %s", addr, string(content[:n]))

				// 将获取的内容转成大写返回
				result := strings.ToUpper(string(content[:n]))
				if result[:n-1] == "EXIT" {
					fmt.Println(addr, "exit")
					gb_info := []byte(fmt.Sprintf("Good bye %s ! See you next time.\n", addr))
					conn.Write(gb_info)
					return
				} else {
					answer := append(content[:n-1], []byte("    ===>    ")...)
					answer = append(answer, []byte(result)...)
					conn.Write(answer)
				}
			}
		}(conn)
	}
}
